﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using blackhouse.BlackApart.Business.MailTemplate;
using blackhouse.BlackApart.Business;
using System.Net.Mail;
using System.Configuration;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;

namespace blackhouse.BlackApart.Actions {
	public class ClientMailReservationAction : ReservationAction {

		#region Fields

		private SmtpClient client = new SmtpClient();
		private MailMessage message = new MailMessage();
		private IMailTemplate template;
		private string generatorUrl;

		#endregion

		protected override void RunForReservation(int reservationId, int initialStatusId) {
			// http://bh-dev.aparts.com.pl/Mails/HtmlMailGenerator.aspx?reservationId=606&templateId=1&skin=ApartsMail
			this.generatorUrl = this.template.GetMailTemplateUrlForReservation(GetReservation());
			this.message.Subject = this.template.MailTitle;
			this.message.Body = this.ReadMailBody(this.generatorUrl);
			this.message.IsBodyHtml = true;
			string[] toMail = this.GetToAddress();
			if (toMail.Length > 0) {
				foreach (string to in toMail) {
					this.message.To.Add(to);
				}
				client.Send(this.message);
			}
			else {
				throw new MissingFieldException("Klient przypisany do rezerwacji nie ma wprowadzonego adresu e-mail");
			}
		}

		protected virtual string[] GetToAddress() {
			string mail = ConfigurationManager.AppSettings["TestMail"];
			if (string.IsNullOrEmpty(mail))
				mail = this.GetReservation().Client.EMail;
			return mail.Split(';');
		}

		private string ReadMailBody(string url) {
			string body = "";
			try {
				WebRequest request = HttpWebRequest.Create(url);
				WebResponse response = request.GetResponse();
				using (StreamReader sr = new StreamReader(response.GetResponseStream())) {
					body = sr.ReadToEnd();
				}
			}
			catch (Exception e) {
				throw new Exception("Błąd przy odczycie szablonu maila, URL: " + url, e);
			}
			body = Regex.Replace(body, "<!DOCTYPE.*>|<form.*>|<input.*>|</form>", "");
			return body;
		}

		public override void Initialize(string initializeData) {
			base.Initialize(initializeData);
			int mailTemplateId = 0;
			if (!Int32.TryParse(initialData[0], out mailTemplateId))
				throw new IndexOutOfRangeException("Z danych inicjacyjnych nie można wyciągnąć informacji o szablonie (templateId). Dane inicjacyjne: " + initializeData + ". W danych inicjacyjnych na trzecim miejscu powinien być zapisany szablon (templateId)");
			this.template = Factory.Instance().GetMailTemplate(mailTemplateId);
			if (client.Port != 25)
				client.EnableSsl = true;
		}

	}
}
